﻿
using Beway.ValueAdded.Model;
using Beway.ValueAdded.Model.ViewModel;
using Beway.ValueAdded.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Beway.ValueAdded.Admin.Controllers
{
    public class DiscountController:BaseController
    {
        ReUserServ Service = SingletonProvider<ReUserServ>.Instance;
        RechargeServ rechSvc = SingletonProvider<RechargeServ>.Instance;
        AdminUserServ admSvc = SingletonProvider<AdminUserServ>.Instance;
        /// <summary>
        /// 扣量项目管理
        /// </summary>
        /// <returns></returns>
        public ActionResult Project()
        {
            return View();
        }

        public JsonResult ReUserList(int? page, int? rows, string UserName)
        {
            int ListCount = 0;
            int adminId = 0;
             
            var d = Service.ReUserList(page ?? 0, rows ?? 0, UserName, adminId, out ListCount);
           
            Dictionary<string, object> json = new Dictionary<string, object>();
            json.Add("total", ListCount);
            json.Add("rows", d);
            return Json(json, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult UpdateReUser(ReUser Model)
        {
            if (CurrentRole == ManagerRoleType.SystemAdmin)
            {
                var model = Service.GetByUserId(Model.UserID);
                model.RechDiscountRate = Model.RechDiscountRate;

                int Result = Service.UpdateReUser(model);
                return Content(Result.ToString());
            }
            else
            {
                return Content("0");
            }
        }

        /// <summary>
        /// 扣量列表明细
        /// </summary>
        /// <returns></returns>
        public ActionResult List()
        {
            ReUserServ ruServ = new ReUserServ();
            var q = ruServ.SelectAll();
            int adminId = 0;
            if (CurrentRole == ManagerRoleType.MerchantAdmin)
            {
                adminId = admSvc.GetByUserName(User.Identity.Name).AdminID;
                if (adminId > 0)
                {
                    q = q.Where(m => m.AdminId == adminId).ToList();
                }
            }

            ViewBag.ReUserList = q; //项目列表

            return View();
        }

        public JsonResult RechargeList(int? page, int? rows, int? userId, string orderNo, string rcTarget, DateTime? beginTime, DateTime? endTime, int rcStatus = 3)
        {
            int ListCount = 0;
            int adminId = 0;

            var d = rechSvc.RechargeList(page ?? 0, rows ?? 0, userId ?? 0, adminId, orderNo, rcTarget, -1, beginTime, endTime, out ListCount, rcStatus);
            Dictionary<string, object> json = new Dictionary<string, object>();
            json.Add("total", ListCount);
            json.Add("rows", d);
            return Json(json, JsonRequestBehavior.AllowGet);
        }

        //导出
        [HttpPost]
        public ActionResult Export(int? userId, string orderNo, string rcTarget, DateTime? beginTime, DateTime? endTime, int rcStatus = 3)
        {
            int ListCount = 0;
            int adminId = 0;
           
            var list = rechSvc.RechargeList(1, 100000000, userId ?? 0, adminId, orderNo, rcTarget, -1, beginTime, endTime, out ListCount,rcStatus);
            string filename = "re" + beway.common.FileUtil.GetFileNameFromSystemAuto();
            return new beway.common.ExcelResult<RechargeView>(list, filename);
        }

        /// <summary>
        /// 补充充值
        /// </summary>
        /// <param name="rcId">充值ID</param>
        /// <returns></returns>
        public JsonResult RechargeAgain(int rcId)
        {
            bool blnRet = false;
            string strMsg = "";
            Recharge re = rechSvc.GetById(rcId);
            if (re != null && re.RCID > 0 && re.RechDiscountFlag == 1)
            {
                //生成新的订单号，欧飞平台不允许重复
                string orderID = "RE" + beway.common.FileUtil.GetFileNameFromSystemAuto() + re.UserID.ToString();
                re.OrderID = orderID;

                //调用充值接口
                if (re.RCType < 3) //1话费，2q币
                {
                    int reRet = 0;
                    ReUser ru = new ReUser (){
                         RechDiscountRate = 0//补充的不再扣量了。。。
                    };
                    string strRet = rechSvc.RechargeTrade(re, ru); //0系统异常，1成功，2充值中，3充值失败，可以退款          

                    int.TryParse(strRet, out reRet);

                    if (reRet == 1)//1成功
                    {
                        blnRet = true;
                        strMsg = "补充充值成功|" + System.DateTime.Now;

                        re.RechDiscountFlag = 2; //补充成功
                    }
                    else if (reRet == 2)//2充值中，
                    {
                        blnRet = true;
                        strMsg = "充值中，请稍后查询充值结果（充值结果未返回前，请不要再次补充！)";

                    }
                    else if (reRet == 3)//3充值失败，可以退款，欧飞返回状态码为9 
                    {
                        strMsg = "充值失败，请稍后重试(欧飞原因)!";
                    }
                    else
                    {
                        strMsg = re.RechargeErrorReason;//记录充值实时返回的错误
                    }

                    re.RechargeErrorReason = strMsg;
                }
                else //礼品卡类
                {
                    //调用提卡接口
                    if (rechSvc.GiftCardTrade(re))
                    {
                        blnRet = true;
                        strMsg = "提卡成功，请将卡号及密码发送客户(注意保密)。";
                    }
                    else
                    {
                        strMsg = "提卡失败，请查看失败原因或联系技术人员查询日志。";
                    }
                }
                //更新充值结果
                bool isUpdate = rechSvc.Update(re);
            }
            else
            {
                strMsg = "抱歉！此记录状态已发生变化，请刷新后重试。";
            }

            return Json(new { msg = strMsg, ret = blnRet }, JsonRequestBehavior.AllowGet);
        }  
    }
}